<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form label-width="80px">
        <el-form-item label="考试名称" class="filter-item">
          <el-select
            v-model="listQuery.condition.paperName"
            style="width: 380px"
            placeholder="请选择考试名称"
          >
            <el-option
              v-for="item in nameList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考试期数" class="filter-item">
          <el-input
            v-model="listQuery.condition.period"
            placeholder="请输入考试期数"
            style="width: 400px;"
            @keyup.enter.native="handleSearch"
          />
        </el-form-item>
        <el-form-item label="类别" class="filter-item">
          <el-select
            v-model="listQuery.condition.type"
            style="width: 280px"
            placeholder="请选择类别"
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-button
          v-waves
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleSearch"
        >
          搜索
        </el-button>
        <el-button
          v-waves
          class="filter-item"
          icon="el-icon-refresh-left"
          @click="resetSearch"
        >
          重置
        </el-button>
      </el-form>
    </div>
    <div class="my-table">
      <div class="table-operate">
        <div class="title">数据列表</div>
        <div class="btns" v-if="hasPerm('admin')">
          <el-button
            class="operate-item"
            style="margin-right: 20px;"
            type="primary"
            icon="el-icon-edit"
            @click="handleCreate"
          >
            新增
          </el-button>
          <el-button
            class="operate-item"
            style="margin-left: 20px;"
            type="primary"
            icon="el-icon-download"
            @click="handleExport"
            :loading="downloadLoading"
          >
            导出
          </el-button>
        </div>
      </div>
      <el-table
        v-loading="listLoading"
        :data="list"
        border
        :header-cell-style="headerCellStyle"
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" width="55">
        </el-table-column>
        <el-table-column label="序号" type="index" align="center" width="60">
          <template slot-scope="{ row, $index }">
            <span>{{ getIndex($index) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="考试名称">
          <template slot-scope="{ row }">
            <span>{{ row.paperName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="考试期数" width="160" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.period }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类别">
          <template slot-scope="{ row }">
            <span>{{ row.type }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="120">
          <template slot-scope="{ row }">
            <span>
              {{ row.createTime | parseTime("{y}-{m}-{d}") }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="hasPerm('admin')"
          label="操作"
          align="center"
          width="340"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="{ row, $index }">
            <el-button type="info" size="mini" @click="exportFile(row,'paperUrl')">
              导出试卷
            </el-button>
            <el-button type="success" size="mini" @click="exportFile(row,'answerUrl')">
              导出答案
            </el-button>
            <el-button type="primary" size="mini" @click="handleUpdate(row)">
              编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(row, $index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageIndex"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <!-- form -->
    <FormDialog ref="tableForm" @afterSubmit="afterSubmit" />
  </div>
</template>

<script>
import waves from "@/directive/waves"; // waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination";
import baseMixin from "@/mixins/list";
import FormDialog from "./modules/FormDialog";
import request from '@/utils/request'

export default {
  name: "Paper",
  components: { Pagination, FormDialog },
  directives: { waves },
  mixins: [baseMixin],
  data() {
    return {
      sortOptions: [
        { label: "ID Ascending", key: "+id" },
        { label: "ID Descending", key: "-id" }
      ],
      Urls: {
        listUrl: "/api/exam/paper/record/page",
        delUrl: "/api/exam/paper/record/delete/",
        exportUrl: '/api/file/batchDownload',
        generateUrl: '/api/exam/paper/record/generate/',
        getByIdUrl: '/api/exam/paper/record/get/'
      },
      confirmLoading: false,
      fileExt: '.zip',
      nameList: [
        {
          id:'贵阳市建筑施工特种作业人员理论考试试卷',
          name: '贵阳市建筑施工特种作业人员理论考试试卷'
        },
        {
          id:'贵阳市建筑施工企业“安管人员”安全生产知识考试试卷',
          name: '贵阳市建筑施工企业“安管人员”安全生产知识考试试卷'
        },
      ],
      typeList: [
        {
          id:'企业主要负责人',
          name: 'A类：企业主要负责人'
        },
        {
          id:'项目负责人',
          name: 'B类：项目负责人'
        },
        {
          id:'机械类专职安全生产管理人员',
          name: 'C1类：机械类专职安全生产管理人员'
        },
        {
          id:'土建类专职安全生产管理人员',
          name: 'C2类：土建类专职安全生产管理人员'
        },
        {
          id:'综合类专职安全生产管理人员',
          name: 'C3类：综合类专职安全生产管理人员'
        },
        {
          id:'建筑电工',
          name: '建筑电工'
        },
        {
          id:'建筑架子工',
          name: '建筑架子工'
        },
        {
          id:'建筑起重司索信号工',
          name: '建筑起重司索信号工'
        },
        {
          id:'建筑起重塔式起重机司机',
          name: '建筑起重塔式起重机司机'
        },
        {
          id:'建筑起重施工升降机司机',
          name: '建筑起重施工升降机司机'
        },
        {
          id:'建筑起重物料提升机司机',
          name: '建筑起重物料提升机司机'
        },
        {
          id:'建筑起重机械安装拆卸工',
          name: '建筑起重机械安装拆卸工'
        },
        {
          id:'建筑焊工',
          name: '建筑焊工'
        },
        {
          id:'建筑土石方机械操作工',
          name: '建筑土石方机械操作工'
        },
        {
          id:'高处作业吊篮安装拆卸工',
          name: '高处作业吊篮安装拆卸工'
        },
        {
          id:'建筑中小型机械操作工',
          name: '建筑中小型机械操作工'
        }
      ]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    sortChange(data) {
      const { prop, order } = data;
      console.log("sort", data);
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "ascending" : "descending";
    },
    /**
     * 导出
     */
    handleExport() {
      let _this = this
      if (_this.multipleSelection.length == 0) {
        _this.$notify.warning({
          message: '请选择导出的数据!'
        })
        return
      }
      let ids = []
      let index = 0
      const answerIds = _this.multipleSelection.map(item => {
        index = item.answerUrl.lastIndexOf('/')
        return item.answerUrl.substring(index+1, item.answerUrl.length)
      })
      const paperIds = _this.multipleSelection.map(item => {
        index = item.paperUrl.lastIndexOf('/')
        return item.paperUrl.substring(index+1, item.paperUrl.length)
      })
      ids = [...paperIds, ...answerIds]
      this.$confirm('如你点击确认后，请稍等...', '确认导出?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        _this.localLoading = true
        _this.downloadLoading = true
        request({
          url: _this.Urls.exportUrl,
          method: 'post',
          data: {
            ids: ids
          },
          responseType: 'blob'
        }).then(res => {
          _this.localLoading = false
          _this.downloadLoading = false
          if (!res) {
            return
          }
          const blob = new Blob([res])
          let fileName = '试卷及答案' + _this.fileExt
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
        }).catch(() => {
          _this.localLoading = false
          _this.downloadLoading = false
        })
      }).catch(() => {});
    },
    /**
     * 导出试卷 或 答案
     * @param {Object} record
     * @param {Object} type => answerUrl or paperUrl
     */
    exportFile(record, type) {
      window.open(record[type],'_self')
      /*
      const _this = this
      _this.localLoading = true
      _this.listLoading = true
      request({
        url: _this.Urls.generateUrl + record.id,
        method: 'get',
        data: {},
      }).then(res => {
        if(res.code === 0) {
          request({
            url: _this.Urls.getByIdUrl + record.id,
            method: 'get',
            data: {},
          }).then(res => {
            _this.localLoading = false
            _this.listLoading = false
            if(res.code === 0) {
              window.open(res.data[type])
            } else {
              _this.$notify.error({
                message: res.msg
              })
            }
          }).catch(() => {
            _this.localLoading = false
            _this.listLoading = false
          })
        } else {
          _this.$notify.error({
            message: res.msg
          })
        }
      }).catch(() => {
        _this.localLoading = false
        _this.listLoading = false
      })
    */},
  }
};
</script>
